<template>
    <a-modal
        :visible="visible"
        :title="dialogTitle"
        :width="800"
        @ok="handleOk"
        @cancel="handleCancel"
        @close="handleCancel"
    >
        <a-row :gutter="16">
            <!-- 设备树 -->
            <a-col :span="6">
                <a-tree
                    :tree-data="treeData"
                    :selected-keys="selectedTreeKeys"
                    :expanded-keys="expandedKeys"
                    default-expand-all
                    expand-all
                    :disabled="isMonitorMode"
                    @select="onTreeSelect"
                    @expand="onTreeExpand"
                />
            </a-col>

            <!-- 变量/设备选择区域 -->
            <a-col :span="18">
                <!-- 设备列表 -->
                <div v-if="isPortSelected">
                    <a-table
                        :columns="deviceColumns"
                        :data-source="deviceList"
                        :row-selection="deviceRowSelection"
                        :row-key="record => record.key"
                        size="small"
                    />
                </div>
                <!-- 变量选择 -->
                <a-tabs v-else default-active-key="variables" @change="onTabChange">
                    <a-tab-pane key="variables" tab="监控点">
                        <a-table
                            :columns="tableColumns"
                            :data-source="variableList"
                            :row-selection="variableRowSelection"
                            size="small"
                        />
                    </a-tab-pane>
                    <a-tab-pane key="monitors" tab="内部变量">
                        <a-table
                            :columns="tableColumns"
                            :data-source="monitorList"
                            :row-selection="monitorRowSelection"
                            size="small"
                        />
                    </a-tab-pane>
                </a-tabs>
            </a-col>
        </a-row>
    </a-modal>
</template>

<script>
export default {
    name: 'AssociativeVarDialog',
    props: {
        visible: {
            type: Boolean,
            default: false
        },
        tableRowSelectType: {
            type: String,
            default: 'checkbox'
        },
        dialogTitle: {
            type: String,
            default: ''
        }
    },
    data() {
        return {
            treeData: [],
            variableList: [],
            deviceList: [], // 设备列表数据
            selectedTreeKey: null,
            selectedTreeKeys: [], // 树组件选中的keys数组
            expandedKeys: [], // 树组件展开的keys数组
            selectedVariableKeys: [],
            selectedMonitorKeys: [],
            selectedDeviceKey: null, // 选中的设备key
            selectedDevice: null,
            currentTab: 'variables',
            deviceOptions: [],
            
            // 静态监控点数据
            monitorList: [
                { key: 'M1', name: 'timestampS',   type: 'string', desc: '时间戳(秒)，字符串类型' },
                { key: 'M2', name: 'timestampMs',  type: 'string', desc: '时间戳(毫秒)，字符串类型' },
                { key: 'M3', name: 'mqttName',     type: 'string', desc: 'mqtt名称' },
                { key: 'M4', name: 'mqttClientId', type: 'string', desc: 'mqtt客户端' },
                { key: 'M5', name: 'mqttUsername', type: 'string', desc: 'mqtt用户名' },
                { key: 'M6', name: 'mqttTopic',    type: 'string', desc: 'mqtt主题' }
            ]
        }
    },
    computed: {
        // 是否选中了端口
        isPortSelected() {
            if (!this.selectedTreeKey || !this.treeData.length) return false
            return this.selectedTreeKey.startsWith('port_')
        },
        
        // 是否为监控点模式
        isMonitorMode() {
            return this.currentTab === 'monitors'
        },
        
        // 表格列配置
        tableColumns() {
            return [
                { title: '名称', dataIndex: 'name', key: 'name' },
                // { title: '数据类型', dataIndex: 'type', key: 'type', width: '20%' },
                { title: '描述', dataIndex: 'desc', key: 'desc', width: '35%' }
            ]
        },
        
        // 变量表格行选择配置
        variableRowSelection() {
            return {
                selectedRowKeys: this.selectedVariableKeys,
                onChange: this.onVariableSelectionChange,
                type: this.tableRowSelectType
            }
        },
        
        // 监控点表格行选择配置
        monitorRowSelection() {
            return {
                selectedRowKeys: this.selectedMonitorKeys,
                onChange: this.onMonitorSelectionChange,
                type: 'radio'
            }
        },

        // 设备列表表格列配置
        deviceColumns() {
            return [
                { title: '设备名称', dataIndex: 'name', key: 'name' },
                // { title: '设备ID', dataIndex: 'id', key: 'id' },
                { title: '描述', dataIndex: 'desc', key: 'desc' }
            ]
        },

        // 设备列表行选择配置
        deviceRowSelection() {
            return {
                selectedRowKeys: this.selectedDeviceKey ? [this.selectedDeviceKey] : [],
                onChange: this.onDeviceSelectionChange,
                type: 'radio'
            }
        }
    },
    watch: {
        visible: {
            async handler(newVal) {
                if (newVal) {
                    this.resetSelection()
                    await this.loadDeviceTree()
                }
            }
        }
    },
    methods: {
        // 加载设备树
        async loadDeviceTree() {
            try {
                const res = await this.$tabManager.edge.getMqttFormatJsonDeviceTree('')
                if (res.code === 0) {
                    const data = JSON.parse(res.data)
                    this.treeData = this.convertToTreeData(data)
                    
                    // 设置所有节点为展开状态
                    this.expandedKeys = this.getAllTreeKeys(this.treeData)
                    
                    // 默认选中第一个端口
                    if (this.treeData.length > 0) {
                        const firstPortKey = this.treeData[0].key
                        // 使用 $nextTick 确保树渲染完成后再选中
                        this.$nextTick(() => {
                            this.selectedTreeKeys = [firstPortKey]
                            this.onTreeSelect([firstPortKey])
                        })
                    }
                } else {
                    this.$message.error(res.msg)
                }
            } catch (error) {
                this.$message.error('加载设备树失败')
            }
        },

        // 获取所有树节点的key用于展开
        getAllTreeKeys(treeData) {
            const keys = []
            const traverse = nodes => {
                nodes.forEach(node => {
                    keys.push(node.key)
                    if (node.children && node.children.length > 0) {
                        traverse(node.children)
                    }
                })
            }
            traverse(treeData)
            return keys
        },

        // 树节点展开/收缩处理
        onTreeExpand(expandedKeys) {
            this.expandedKeys = expandedKeys
        },
        
        // 转换树数据格式
        convertToTreeData(ports, level = 1) {
            return ports.map(port => ({
                title: port.title,
                key: level === 1 ? `port_${port.key}` : `device_${port.key}`,
                children: port.children ? this.convertToTreeData(port.children, level + 1) : []
            }))
        },
        
        // 树节点选择
        async onTreeSelect(selectedKeys) {
            if (!selectedKeys.length) return
            
            this.selectedTreeKey = selectedKeys[0]
            this.selectedTreeKeys = selectedKeys
            
            if (this.isPortSelected) {
                // 端口选中，清空变量列表，从树结构中获取设备列表
                this.variableList = []
                this.deviceList = this.getDevicesFromPort(this.selectedTreeKey)
                return
            }
            
            // 设备选中，加载变量列表
            const deviceKey = this.selectedTreeKey.replace('device_', '')
            await this.loadVariables(deviceKey)
        },

        // 从树结构中获取指定端口下的设备列表
        getDevicesFromPort(portKey) {
            const port = this.treeData.find(node => node.key === portKey)
            if (!port || !port.children) return []
            
            const devices = port.children.map(device => ({
                id: device.key.replace('device_', ''), // 添加id属性
                desc: '绑定设备状态',
                name: device.title,
                key: device.key.replace('device_', '')
            }))

            // 如果有设备，默认选中第一个
            if (devices.length > 0) {
                this.selectedDeviceKey = devices[0].key // 修复：使用key而不是id
                this.selectedDevice = devices[0]
            }
            
            return devices
        },
        
        // 加载变量列表
        async loadVariables(deviceKey) {
            try {
                const res = await this.$tabManager.edge.getMqttFormatJsonDevicesVarJson(deviceKey)
                if (res.code === 0) {
                    const data = JSON.parse(res.data)
                    this.variableList = data.map(item => ({
                        key: item.id,
                        name: item.name,
                        type: item.type,
                        desc: item.desc,
                        varId: item.id
                    }))
                    
                    // 如果有变量，默认选中第一个
                    if (this.variableList.length > 0) {
                        this.selectedVariableKeys = [this.variableList[0].key]
                    }
                } else {
                    this.$message.error(res.msg)
                }
            } catch (error) {
                this.$message.error('加载变量列表失败')
            }
        },
        
        // 标签页切换
        onTabChange(activeKey) {
            this.currentTab = activeKey
            // 切换到监控点tab时，默认选中第一个
            if (activeKey === 'monitors' && this.monitorList.length > 0) {
                this.selectedMonitorKeys = [this.monitorList[0].key]
            }
        },
        
        // 变量选择变化
        onVariableSelectionChange(selectedKeys) {
            this.selectedVariableKeys = selectedKeys
        },
        
        // 监控点选择变化
        onMonitorSelectionChange(selectedKeys) {
            this.selectedMonitorKeys = selectedKeys
        },

        // 设备列表选择变化
        onDeviceSelectionChange(selectedKeys) {
            if (selectedKeys.length > 0) {
                this.selectedDeviceKey = selectedKeys[0]
                this.selectedDevice = this.deviceList.find(item => item.key === selectedKeys[0])
            } else {
                this.selectedDeviceKey = null
                this.selectedDevice = null
            }
        },
        
        // 设备级联选择
        onDeviceSelect(value) {
            const [devId, deviceId] = value
            // 构造与原组件兼容的设备对象结构
            this.selectedDevice = {
                id: deviceId,
                devId: devId,
                name: '', // 需要从级联选择器获取
                devName: '' // 需要从级联选择器获取
            }
        },
        
        // 确认选择
        handleOk() {
            console.log('isPortSelected', this.isPortSelected)
            console.log('selectedDevice', this.selectedDevice)
            if (this.isPortSelected && this.selectedDevice) {
                // 设备选择模式
                const data = {
                    devId: this.selectedDevice.id,
                    devName: this.selectedDevice.name
                }
                this.$emit('handleDevOk', JSON.stringify(data))
                return
            }
            
            console.log('isMonitorMode', this.isMonitorMode)
            if (this.isMonitorMode) {
                // 监控点选择模式
                const selectedData = this.selectedMonitorKeys.map(key => {
                    const item = this.monitorList.find(m => m.key === key)
                    const data = {
                        type: item.type,
                        varId: item.key,
                        default: item.name,
                        title: ''
                    }
                    return data
                })
                console.log('isMonitorMode selectedData', this.selectedMonitorKeys)
                this.$emit('handleOk', JSON.stringify(selectedData), 'radio', true)
                return
            }

            // 变量选择模式
            const deviceKey = this.selectedTreeKey.replace('device_', '')
            const selectedData = this.selectedVariableKeys.map(key => {
                const item = this.variableList.find(v => v.key === key)
                const data = {
                    type: item.type,
                    varId: item.key,
                    default: item.name,
                    title: item.name,
                    devId: deviceKey
                }
                return data
            })
            console.log('variable selectedData', selectedData)
            this.$emit('handleOk', JSON.stringify(selectedData), this.tableRowSelectType, false)
        },
        
        // 取消
        handleCancel() {
            this.$emit('handleCancel')
        },
        
        // 重置选择状态
        resetSelection() {
            this.selectedTreeKey = null
            this.selectedTreeKeys = []
            this.expandedKeys = []
            this.selectedVariableKeys = []
            this.selectedMonitorKeys = []
            this.selectedDeviceKey = null
            this.selectedDevice = null
            this.currentTab = 'variables'
            this.variableList = []
            this.deviceList = []
        }
    }
}
</script>

<style scoped lang="scss">
::v-deep .ant-modal-body {
    padding: 16px;
}
::v-deep .ant-table-small {
    .ant-table-thead > tr > th,
    .ant-table-tbody > tr > td {
        padding: 8px;
    }
}
</style>
    